package pl.kosmowska.ewelina.client.views.widgets;

import pl.kosmowska.ewelina.client.ViewMessages;
import pl.kosmowska.ewelina.client.app.ClientFactory;
import pl.kosmowska.ewelina.client.app.requestfactory.dto.UserDataProxy;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

public class LoginWidget extends Composite {

  private static LoginWidgetUiBinder uiBinder = GWT.create(LoginWidgetUiBinder.class);
  @UiField HTML htmlNick;
  @UiField HTML htmlUrl;
  @UiField LoadingWidget wLoading;


  private ClientFactory clientFactory;
  

  interface LoginWidgetUiBinder extends UiBinder<Widget, LoginWidget> {
  }

  public LoginWidget() {
    initWidget(uiBinder.createAndBindUi(this));   
  }

  public void setClientFactory(ClientFactory clientFactory) {
    this.clientFactory = clientFactory;
    
    createUser();
  }
  

  private void createUser() {
    wLoading.showLoading(true,ViewMessages.LOADING_MESSAGE);
    Request<UserDataProxy> req = clientFactory.getRequestFactory().getUserDataRequest().createUserData();
    req.fire(new Receiver<UserDataProxy>() {
      public void onSuccess(UserDataProxy data) {
        wLoading.showLoading(false);
        process(data);
      }
      public void onFailure(ServerFailure error) {
        wLoading.showError(ViewMessages.ERROR_TIME_OUT);
        super.onFailure(error);
      }
    });
  }

  private void process(UserDataProxy userData) {
    if (userData != null && 
        userData.getId() != null && 
        userData.getId().matches(".*([0-9]+).*") == true) {
      setLoggedIn(userData);
    } else {
      setLoggedOut(userData);
    }
    
    clientFactory.setUserData(userData);
  }


  private void setLoggedOut(UserDataProxy userData) {
    if (userData == null) {
      // this shouldn't happen, b/c we need the urls
      return;
    }

    String url = userData.getLoginUrl();
    String qs = Window.Location.getQueryString();
    String token = History.getToken();
    if (qs != null) {
      url += URL.encode(qs);
    }
    if (token != null && token.length() > 0) {
      url += URL.encode("#" + token);
    }
    
    // This is a must, always clean before draw
    SafeHtmlBuilder builder = new SafeHtmlBuilder();
    builder.appendHtmlConstant("<a href='" + url + "'>")
    .appendEscaped("Zaloguj się")
    .appendHtmlConstant("</a>");
    htmlUrl.setHTML(builder.toSafeHtml());
  }


  private void setLoggedIn(UserDataProxy userData) {
    if (userData == null) {
      return;
    }

    setNick(userData);

    String url = userData.getLogoutUrl();
    String qs = Window.Location.getQueryString();
    if (qs != null) {
      url += URL.encode(qs);
    }

    SafeHtmlBuilder builder = new SafeHtmlBuilder();
    builder.appendHtmlConstant("<a href='" + url + "'>")
    .appendEscaped("Wylogowanie")
    .appendHtmlConstant("</a>");
    htmlUrl.setHTML(builder.toSafeHtml());
  }

  private void setNick(UserDataProxy userData) {
    if (userData == null) {
      return;
    }

    String nick = userData.getGoogleNickname();

    // This is a must, always clean before draw
    SafeHtmlBuilder builder = new SafeHtmlBuilder();
    builder.appendEscaped(nick);

    htmlNick.setHTML(builder.toSafeHtml());
  }

}
  